package com.sdgakj.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class UploadFileUtil {
	
	/**
	 * 
	 * 上传文件
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static List<String> upload(HttpServletRequest request) throws IOException {
		List<String> urls = new ArrayList<String>();
		// 设置上下方文
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());

		// 检查form是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {

				// 由CommonsMultipartFile继承而来,拥有上面的方法.
				MultipartFile file = multiRequest.getFile(iter.next());
				if(file != null){  
		            //取得当前上传文件的文件名称  
		            String myFileName = file.getOriginalFilename();  
		            //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
		            if(myFileName.trim() !=""){  
		                //重命名上传后的文件名  
		                String fileName = String.valueOf(System.currentTimeMillis());  
		                //定义上传路径  
		                StringBuilder path = new StringBuilder();
		                StringBuilder url = new StringBuilder();
		                path.append(PropertiesUtil.getUploadImagePath());
		                path.append(fileName);
		                File localFile = new File(path.toString());  
		                file.transferTo(localFile);  
		                
		                url.append(PropertiesUtil.getUploadImageUrl());
		                url.append(fileName);
		                
		                urls.add(url.toString());
		            }  
		        }

			}
		}
		
		return urls;
	} 
}
